import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
function hasUrl(url:string,next:Function){
  let result=JSON.parse((sessionStorage.getItem('userinfo')+'')).menus_url.some((item:any)=>url==item)
  if(result){
    next()
  }else{
    next('/home')
  }
}
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/menu',
        name: '菜单管理',
        component: () => import('../views/menu/menu.vue'),
        beforeEnter:(to,from,next)=>{
          hasUrl('/menu',next)
        }
      },
      {
        path: '/home',
        component: () => import('../views/home.vue'),
      },
      {
        path: '/role',
        name: '角色管理',
        component: () => import('../views/role/role.vue'),
        beforeEnter:(to,from,next)=>{
          hasUrl('/role',next)
        }
      },
      {
        path: '/admin',
        component: () => import('../views/user/user.vue'),
        name: '管理员管理',
        beforeEnter:(to,from,next)=>{
          hasUrl('/admin',next)
        }
      },
      {
        path:'',
        redirect:'/home'
      }
    ]
  },
  {
    path:'',
    redirect:'/index',
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
// 全局登录拦截
router.beforeEach((to,from,next)=>{
  if(to.path=='/login'){
    next()
    return
  }
  if(sessionStorage.getItem('userinfo')){
    next()
    return
  }
  next('/login')
})
export default router
